import React, { useEffect, useState } from "react";
import { Layout, Menu } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import axios from "axios";
import { HomeOutlined, UserOutlined } from "@ant-design/icons";
import "./index.css";
import { connect } from "react-redux";

const { SubMenu } = Menu;
const { Sider } = Layout;
const iconList = {
  "/home": <HomeOutlined />,
  "/user-manage/list": <UserOutlined />,
  "/right-manage/role/list": <HomeOutlined />,
  "/right-manage/right/list": <HomeOutlined />,
};
function SideMenu(props) {
  // 返回一个函数用来实现编程式导航
  let navigate = useNavigate();
  // 获取当前 location 信息，对标5.x中的路由组件的`location`属性
  let location = useLocation();
  useEffect(() => {
    axios.get("http://localhost:5000/rights?_embed=children").then((res) => {
      setMenu(res.data);
    });
  }, []);

  const [menu, setMenu] = useState([]);
  const {
    role: { rights },
  } = JSON.parse(localStorage.getItem("token"));

  const checkPagePermisson = (item) => {
    return item.pagepermisson && rights.includes(item.key);
  };

  const renderMenu = (menuList) => {
    return menuList.map((item) => {
      // item.children?.length > 0先判断有没有孩子 有的话才执行后面的
      if (item.children?.length > 0 && checkPagePermisson(item)) {
        return (
          <SubMenu key={item.key} icon={iconList[item.key]} title={item.title}>
            {renderMenu(item.children)}
          </SubMenu>
        );
      }
      return (
        checkPagePermisson(item) && (
          <Menu.Item
            key={item.key}
            icon={iconList[item.key]}
            onClick={() => navigate(item.key)}
          >
            {item.title}
          </Menu.Item>
        )
      );
    });
  };
  //console.log(location); //获取路由地址http://localhost:3000/#/后的地址
  // defaultOpenKeys 默认展开的一级菜单
  // selectedKeys 默认展开的二级菜单
  // 注意受控和非受控
  // 例如： 默认高亮的二级菜单的地址为location.pathname如/user-manage/list ，则默认展开的一级菜单地址为/user-manage 应对location.pathname做处理   '/user-manage/list'.split('/')[1]可得
  const selectedKeys = [location.pathname];
  const openKeys = ["/" + location.pathname.split("/")[1]]; //别忘了加'/'
  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
      <div style={{ display: "flex", height: "100%", flexDirection: "column" }}>
        <div className="logo">新闻发布管理系统</div>
        <div style={{ flex: 1, overflow: "auto" }}>
          <Menu
            theme="dark"
            mode="inline"
            defaultOpenKeys={openKeys}
            selectedKeys={selectedKeys}
          >
            {renderMenu(menu)}
          </Menu>
        </div>
      </div>
    </Sider>
  );
}

const mapStateToProps = ({ CollApsedReducer: { isCollapsed } }) => ({
  isCollapsed,
});

export default connect(mapStateToProps)(SideMenu);
